// shell.c
#include <stdio.h>
#include <stdlib.h>     // exit()
#include <unistd.h>     // fork(), execvp()
#include <sys/wait.h>   // wait()
#include <string.h>  //strtok()
#include <fcntl.h>
#include "shell.h"

void run_shell() 
{
   char command[1024];
   char* args[64];

   while(1)
   {
          char cwd[1024];
          if(getcwd(cwd, sizeof(cwd)) != NULL)
          { 
                printf("[%s] myshell> ",cwd);
          }
          else
          {
                perror("getcwd failed");     
	        printf("myshell> ");
          }

 
	  fgets(command, sizeof(command), stdin);

	  if(command[strlen(command) - 1] == '\n')
	  {
		 command[strlen(command) - 1] = '\0';
	  }

	  if(strcmp(command, "exit") == 0) break;
	  
          char* redirect_pos = strchr(command, '>');
	  char filename[128] = {0};

	  if(redirect_pos)
	  {
		  *redirect_pos = '\0';
		  redirect_pos++;
		  while(*redirect_pos == ' ') redirect_pos++;
		  strncpy(filename, redirect_pos, sizeof(filename) - 1);
	  }

	  int i = 0;
	  char* token = strtok(command, " ");
       	  while(token != NULL)
	  {
	  args[i++] = token;
		  token = strtok(NULL, " ");
	  }
	  args[i] = NULL;

	  pid_t pid = fork();
	  if(pid == 0)
	  {
		  if(filename[0] != '\0')
		  {
			  int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644);
			  if(fd < 0)
			  {
				  perror("open failed");
				  exit(1);
			  }
			  dup2(fd, STDOUT_FILENO);
			  close(fd);
		  }
                             
		  execvp(args[0], args);
		  perror("exec failed");
		  exit(1);
          }
	  else if(pid > 0)
	  {
		  wait(NULL);
	  }
	  else
	  {
		  perror("fork failed");
	  }
   }
}

